package com.msmall.community.user.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.msmall.base.dao.hibernate.BaseDaoHibernate;
import com.msmall.community.user.dao.UserDao;
import com.msmall.community.user.model.LoginInfo;
import com.msmall.community.user.model.UserInfo;
import com.msmall.community.user.model.UserProfile;
import com.msmall.community.user.model.UserSetting;

public class UserDaoHibernate extends BaseDaoHibernate implements UserDao{
	public UserDaoHibernate(){
		super(UserInfo.class);
	}

	public UserProfile loadProfileByUserid(Long userid) throws Exception{
		try{
			String queryString = "from UserProfile p where p.userid=?";
			List list = super.getHibernateTemplate().find(queryString, userid);
			if(list != null && list.size() > 0)
				return (UserProfile) list.get(0);
			return null;
		}catch(Exception e){
			throw e;
		}
	}
	/**
	 * 获得最近一次登录信息
	 */
	public LoginInfo loadLastLoginInfo(Long userid) throws Exception{
		try{
			String queryString = "from LoginInfo p where p.userid=? order by p.loginTime desc";
			Session session = getSession();
			Query query = session.createQuery(queryString);
			query.setParameter(0, userid);
	 		query.setFirstResult(0).setMaxResults(1);
	 		List list = query.list();
	 		releaseSession(session);
			if(list != null && list.size() > 0)
				return (LoginInfo) list.get(0);
			return null;
		}catch(Exception e){
			throw e;
		}
	}
	
	/**
	 * 获得用户的所有设置信息等
	 * @param userid
	 * @return
	 */
	public List<UserSetting> getSettingByUserid(Long userid)throws Exception{
		try{
			String str = "from UserSetting p where p.userid=?";
			List list = getHibernateTemplate().find(str, new Object[]{userid});
			return list;
		}catch(Exception e){
			throw e;
		}
	}
	/**
	 * key : ConstantDB.USER_SETTING_KEY_
	 */
	public UserSetting getSetting(Long userid, String key)throws Exception{
		try{
			String str = "from UserSetting p where p.userid=? and p.propertyKey=?";
			List list = getHibernateTemplate().find(str, new Object[]{userid, key});
			if(list != null && list.size() > 0)
				return (UserSetting) list.get(0);
			return null;
		}catch(Exception e){
			throw e;
		}
	}
}
